package com.hg.concurent.demo7;

import cn.hutool.core.thread.ThreadUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: skh
 * @Date: 2019/12/23 10:36
 * @Description:
 */
public class ReentrantReadWriterLockDemo {

    public static void main(String[] args) {
        RWDictionary rwDictionary = new RWDictionary();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> {
                rwDictionary.put(String.valueOf(finalI), finalI);
            }, String.valueOf(i)).start();
        }

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(() -> {
                rwDictionary.get(String.valueOf(finalI));
            }, String.valueOf(i)).start();
        }
    }
}

class RWDictionary {
    private final Map<String, Integer> m = new HashMap<String, Integer>();
    private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    private final Lock r = rwl.readLock();
    private final Lock w = rwl.writeLock();

    public Integer get(String key) {
        r.lock(); //读取时加读锁
        try {
            System.out.println(Thread.currentThread().getName()+"开始读取数据");
            return m.get(key);
        } finally {
            r.unlock();
        }
    }

    public Integer put(String key, Integer value) {
        w.lock(); //写时加写锁
        try {
            System.out.println(Thread.currentThread().getName()+"开始写入数据");
            m.put(key, value);
            System.out.println(Thread.currentThread().getName()+"写入数据成功");
            return value;
        } finally {
            w.unlock();
        }
    }

}